package guestbook;

import com.google.api.client.auth.oauth.OAuthCallbackUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.http.HttpResponseException;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Alejandro Gomez (alejandro.gomez@fdvsolutions.com)
 *         Date: 8/18/11
 *         Time: 6:02 PM
 */
public class AccessGrantedServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        try {
            OAuthCallbackUrl url = new OAuthCallbackUrl(Auth.getFullURL(request));
            UserCredentials temporaryCredentials = UserCredentials.forCurrentUser();
            if (!url.token.equals(temporaryCredentials.token)) {
                // OAuth token belongs to a different user from the logged-in user
                String fullUrl = Auth.getFullURL(request);
                UserService userService = UserServiceFactory.getUserService();
                response.sendRedirect(userService.createLogoutURL(fullUrl));
                return;
            }
            // gets an access OAuth token upgraded from a temporary token
            GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
            accessToken.signer = Auth.createSigner(temporaryCredentials);
            accessToken.consumerKey = Constants.ENTER_DOMAIN;
            accessToken.temporaryToken = temporaryCredentials.token;
            accessToken.verifier = url.verifier;
            Auth.executeGetToken(accessToken, temporaryCredentials);
            // redirect back to application, but clear token and verifier query parameters
            url.setRawPath("/");
            url.verifier = null;
            url.token = null;
            response.sendRedirect(url.build());
        } catch (HttpResponseException e) {
            Auth.newIOException(e);
        }
    }
}
